package com.dubbo;

/**
 * @author caoqianhuan
 * @date 2022/9/27
 * @Description:
 */
public class ThreadLocalUsage {
    private static ThreadLocal<String> threadLocal = new ThreadLocal<>();
    //threadLocal静态变量 线程所私有 内部是通过 Thread.concurrentThread() 获得当前线程 并使用threadLocal对象来操作 ThreadLocalMap
    //ThreadLocalMap 对象的引用在Thread中
    private static int i; //非ThreadLocal静态变量 线程有共有

    public static void main(String[] args) throws InterruptedException {

        //从局部变量或者实例成员变量的形式使用ThreadLocal 比较麻烦 需要为每个线程创建一次
        //可以使用静态成员变量 类加载时 被再加到类对象中
        Thread thread1 = new Thread(() -> {
           //threadLocal = new ThreadLocal<>();
            i = 1;
            System.out.println(i);
           threadLocal.set("我是thread1");
            System.out.println(threadLocal.get());
        });
        //threadLocal = new ThreadLocal<>();
        thread1.start();
        thread1.join();
        System.out.println(i);
        i = 2;
        System.out.println(i);
        System.out.println(threadLocal.get());
        threadLocal.set("我是main");
        System.out.println(threadLocal.get());
    }
}
